<template>
  <div class="template-config">
    <!-- 搜索欄 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入模板名称"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按鈕 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增
      </el-button>
      <div class="right-tools">
        <el-icon><Refresh /></el-icon>
        <el-icon><Setting /></el-icon>
        <el-icon><FullScreen /></el-icon>
        <el-icon><Grid /></el-icon>
      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="templateCode" label="模板编号" width="180" />
      <el-table-column prop="templateName" label="模板名称" width="180" />
      <el-table-column prop="type" label="类型" width="120" />
      <el-table-column prop="printer" label="打印机" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" sortable />
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleConfig(scope.row)">
            配置模版
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            刪除
          </el-button>
          <el-button
            v-if="scope.row.isDefault"
            type="warning"
            link
            @click="handleCancelDefault(scope.row)"
          >
            取消默认
          </el-button>
          <el-button
            v-else
            type="success"
            link
            @click="handleSetDefault(scope.row)"
          >
            设为默认
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分頁 -->
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ total }} 条
      </div>
      <div class="pagination-content">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="pagination-goto">
        <span>前往</span>
        <el-input v-model="goToPage" class="goto-input" />
        <span>页</span>
      </div>
    </div>

    <el-dialog v-model="addDialogVisible" title="新增模板" width="500px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="模板编号">
          <el-input v-model="addForm.templateCode" />
        </el-form-item>
        <el-form-item label="模板名称">
          <el-input v-model="addForm.templateName" />
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="addForm.type" />
        </el-form-item>
        <el-form-item label="打印机">
          <el-input v-model="addForm.printer" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" title="編輯模板" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="模板编号">
          <el-input v-model="editForm.templateCode" />
        </el-form-item>
        <el-form-item label="模板名称">
          <el-input v-model="editForm.templateName" />
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="editForm.type" />
        </el-form-item>
        <el-form-item label="打印机">
          <el-input v-model="editForm.printer" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Search, Plus, Refresh, Setting, FullScreen, Grid } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

/**
 * 此页面对应系统管理下的模板配置
 */
// 搜索關鍵字
const searchKeyword = ref('')

// 原始數據
const allTableData = ref([
  {
    templateCode: 'XP1029304-001',
    templateName: '托运单默认模板',
    type: '托运单',
    printer: 'Micond-02',
    createTime: '2025/06/15 19:00:00',
    isDefault: true
  },
  {
    templateCode: 'XP1029304-001',
    templateName: '随车清单默认模板',
    type: '随车清单',
    printer: 'Micond-02',
    createTime: '2025/06/15 19:00:00',
    isDefault: false
  },
  {
    templateCode: 'XP1029304-001',
    templateName: '小票默认模板',
    type: '小票',
    printer: 'Micond-02',
    createTime: '2025/06/15 19:00:00',
    isDefault: false
  },
  {
    templateCode: 'XP1029304-001',
    templateName: '货物标签默认模板',
    type: '货物标签',
    printer: 'Micond-02',
    createTime: '2025/06/15 19:00:00',
    isDefault: false
  }
])
// 顯示數據
const tableData = ref([...allTableData.value])

// 分頁相關
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(50)
const goToPage = ref('')

// 新增彈窗
const addDialogVisible = ref(false)
const addForm = ref({
  templateCode: '',
  templateName: '',
  type: '',
  printer: '',
  isDefault: false
})

// 編輯彈窗
const editDialogVisible = ref(false)
const editForm = ref({
  templateCode: '',
  templateName: '',
  type: '',
  printer: '',
  createTime: '',
  isDefault: false
})
let editIndex = -1

// 搜索
const handleSearch = () => {
  if (!searchKeyword.value) {
    tableData.value = [...allTableData.value]
    return
  }
  tableData.value = allTableData.value.filter(item =>
    item.templateName.includes(searchKeyword.value)
  )
}

// 重置
const handleReset = () => {
  searchKeyword.value = ''
  tableData.value = [...allTableData.value]
}

// 新增
const handleAdd = () => {
  addForm.value = {
    templateCode: '',
    templateName: '',
    type: '',
    printer: '',
    isDefault: false
  }
  addDialogVisible.value = true
}

// 提交新增
const handleAddSubmit = () => {
  if (
    !addForm.value.templateCode ||
    !addForm.value.templateName ||
    !addForm.value.type ||
    !addForm.value.printer
  ) {
    ElMessage.warning('請填寫完整信息')
    return
  }
  // 自動生成當前時間
  const now = new Date()
  const pad = (n: number) => n.toString().padStart(2, '0')
  const createTime = `${now.getFullYear()}/${pad(now.getMonth() + 1)}/${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
  const newData = { ...addForm.value, createTime, isDefault: false }
  tableData.value.push(newData)
  allTableData.value.push(newData)
  addDialogVisible.value = false
  ElMessage.success('新增成功')
}

// 配置模版
const handleConfig = (row: any) => {
  editIndex = tableData.value.findIndex(
    item =>
      item.templateCode === row.templateCode &&
      item.templateName === row.templateName
  )
  editForm.value = { ...row }
  editDialogVisible.value = true
}

// 刪除
const handleDelete = (row: any) => {
  // 根據唯一標識刪除
  tableData.value = tableData.value.filter(
    item => !(
      item.templateCode === row.templateCode &&
      item.templateName === row.templateName
    )
  )
  allTableData.value = allTableData.value.filter(
    item => !(
      item.templateCode === row.templateCode &&
      item.templateName === row.templateName
    )
  )
  ElMessage.success('刪除成功')
}

// 取消默認
const handleCancelDefault = (row: any) => {
  row.isDefault = false
  ElMessage.success('已取消默认设置')
}

const handleSetDefault = (row: any) => {
  row.isDefault = true
  ElMessage.success('已设为默认')
}

// 分頁大小改變
const handleSizeChange = (val: number) => {
  pageSize.value = val
}

// 當前頁改變
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 提交編輯
const handleEditSubmit = () => {
  if (
    !editForm.value.templateCode ||
    !editForm.value.templateName ||
    !editForm.value.type ||
    !editForm.value.printer
  ) {
    ElMessage.warning('請填寫完整信息')
    return
  }
  if (editIndex !== -1) {
    // 保留原有 createTime
    editForm.value.createTime = tableData.value[editIndex].createTime
    tableData.value[editIndex] = { ...editForm.value }
    // 同步 allTableData
    const allIndex = allTableData.value.findIndex(
      item =>
        item.templateCode === editForm.value.templateCode &&
        item.templateName === editForm.value.templateName
    )
    if (allIndex !== -1) {
      allTableData.value[allIndex] = { ...editForm.value }
    }
  }
  editDialogVisible.value = false
  ElMessage.success('修改成功')
}
</script>

<style scoped>
.template-config {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.right-tools {
  display: flex;
  gap: 15px;
  color: #606266;
  font-size: 18px;
}

.right-tools .el-icon {
  cursor: pointer;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #606266;
}

.pagination-goto {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.goto-input {
  width: 50px;
  margin: 0 8px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #4066FF;
  --el-button-border-color: #4066FF;
  --el-button-hover-bg-color: #5C7CFF;
  --el-button-hover-border-color: #5C7CFF;
}
</style> 